package org.lyj.samples;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.http.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Map;

public class DownloadVerticle extends AbstractVerticle {

    private static final Logger logger = LoggerFactory.getLogger(DownloadVerticle.class);
    private static final String FILE_PATH = "/Apache/apache-maven-3.6.1-bin.tar.gz";

    @Override
    public void start(Future<Void> startFuture) throws Exception {
        Future.<Boolean>future().setHandler(init -> {
            if(init.succeeded() && init.result()) {
                Future<Void> future = Future.future();
                response(future);
                CompositeFuture.all(Lists.newArrayList(future)).setHandler(server -> {
                    if (server.succeeded()) {
                        logger.info("server 全部部署成功");
                        startFuture.complete();
                    } else {
                        server.cause().printStackTrace();
                        logger.error(server.cause().getMessage());
                        startFuture.fail(server.cause());
                    }
                });
            } else {
                init.cause().printStackTrace();
                logger.error(init.cause().getMessage());
                startFuture.fail(init.cause());
            }
        }).complete(true);
    }

    private void response(Future<Void> future) {
        vertx.createHttpServer().requestHandler(req -> {
            req.exceptionHandler(Throwable::printStackTrace);
            HttpMethod method = req.method();
            String urlPath = req.path();
            logger.info("method: " + method + " , url: " + urlPath);
            if("/".equals(urlPath)) {
                File file = new File(FILE_PATH);
                if(file.exists()) {
                    try {
                        req.response().sendFile(file.getCanonicalPath());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //发送自定义对象,需要编解码器
                    DeliveryOptions options = new DeliveryOptions().setCodecName("mapCodec");//必须指定名字
                    Map<String,String> map = Maps.newHashMap();
                    map.put("test","Hello");
                    vertx.eventBus().send("anAddress", map, options, res -> {
                        if(res.succeeded()) {
                            logger.info("receive apply success: {}", res.result().body());
                        } else {
                            logger.error("error: " + res.cause().getMessage());
                        }
                    });
                } else {
                    req.response().setStatusCode(200).end("not found file");
                }
            }
        }).listen(8080, server -> {
            if (server.succeeded()) {
                logger.debug("Download Server 7778");
                future.complete();
            } else {
                logger.error("server start failure");
                server.cause().printStackTrace();
                logger.error(server.cause().getMessage());
                future.fail(server.cause());
            }
        });
    }
}
